package leetcode.code1296;

import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.TreeMap;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public boolean isPossibleDivide(int[] nums, int k) {
		TreeMap<Integer, Integer> map = new TreeMap<>();
		for (int num : nums) {
			map.put(num, map.getOrDefault(num, 0) + 1);
		}
		Queue<Map.Entry<Integer, Integer>> queue = new LinkedList<>();
		while (!queue.isEmpty() || !map.isEmpty()) {
			while (queue.size() < k) {
				if (map.isEmpty()) {
					return false;
				}
				queue.add(map.pollFirstEntry());
			}
			Map.Entry<Integer, Integer> first = queue.poll();
			int sub = first.getValue();
			int start = first.getKey();
			int len = 1;
			while (len < k) {
				Map.Entry<Integer, Integer> next = queue.poll();
				if (next.getKey() != start + 1) {
					return false;
				}
				int rest = next.getValue() - sub;
				if (rest < 0) {
					return false;
				}
				if (rest > 0) {
					queue.add(Map.entry(next.getKey(), rest));
				}
				start = next.getKey();
				len++;
			}
		}
		return true;
	}

	@Override
	public void debug4() {
		H.compare(true, this.isPossibleDivide(H.str2array3("[1,2,3,3,4,4,5,6]"), 4));
		H.compare(true, this.isPossibleDivide(H.str2array3("[3,2,1,2,3,4,3,4,5,9,10,11]"), 3));
		H.compare(false, this.isPossibleDivide(H.str2array3("[1,2,3,4]"), 3));
		H.compare(true, this.isPossibleDivide(H.str2array3("[3,3,2,2,1,1]"), 3));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

}
